package com.gdt.bdMessageQueue.advisory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.CommandTypes;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.DataStructure;
import org.apache.activemq.command.RemoveInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gdt.bdMessageQueue.pojo.ActiveMqMonitor;
import com.gdt.bdMessageQueue.service.ActiveMqMonitorService;

/**
 * 监听服务的开启和关闭
 * @author Joy
 *
 */
@Component
public class ConsumerAdvisoryListener implements MessageListener {
	

	@Autowired
	ActiveMqMonitorService acMService;
	
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public void onMessage(Message message) {
		ActiveMQMessage msg = (ActiveMQMessage) message;
		DataStructure ds = msg.getDataStructure();
		if (ds != null) {
			switch (ds.getDataStructureType()) {
			case CommandTypes.CONSUMER_INFO:
				ConsumerInfo consumerInfo = (ConsumerInfo) ds;
				System.out.println("Consumer '" + consumerInfo.getConsumerId()
						+ "' subscribed to '" + consumerInfo.getDestination()
						+ "'");
				//ActiveMQMessage acM =new ActiveMQMessage();
				
				String queueName = consumerInfo.getDestination().toString().substring(8);
				ActiveMqMonitor monitor = acMService.getActiveMqMonitorByQueueName(queueName);
				if(monitor!=null){
					try {
						String status ="1";  //"1"的状态代表已开启服务
						String customerId = consumerInfo.getConsumerId().toString();
						Date now = dateFormat.parse(dateFormat.format(new Date()));
						monitor.setUpdateTime(now);
						acMService.updateStartStatus(queueName, status,customerId, now);
						
					} catch (Exception e) {
						System.err.println("服务开启的时候更新状态失败");
						e.printStackTrace();
					}
				}
				//消费者端信息存入数据库，表明北斗服务平台已开启对网省公司的监听服务
				break;
			case CommandTypes.REMOVE_INFO:
				RemoveInfo removeInfo = (RemoveInfo) ds;
				ConsumerId consumerId = ((ConsumerId) removeInfo.getObjectId());
				System.out
						.println("Consumer '" + consumerId + "' unsubscribed");
				String cId = ((ConsumerId) removeInfo.getObjectId()).toString();
				ActiveMqMonitor aqM = acMService.getActiveMqMonitorBycustomerId(cId);
				if(aqM !=null){
					try {
						Date now = dateFormat.parse(dateFormat.format(new Date()));
						String status = "2";
						acMService.updateStopStatus(cId,status,now);
					} catch (Exception e) {
						System.err.println("更改activeMq状态信息出错");
						
					}
				}
				//todo
				//更改数据库表信息，停止北斗平台服务端的服务
				break;
			default:
				System.out.println("Unkown data structure type");
			}
		} else {
			System.out.println("No data structure provided");
		}
	}
}
